package com.ruoyi.yipaiju.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.domain.entity.XcxUser;
import com.ruoyi.common.core.page.TableDataApi;
import com.ruoyi.yipaiju.domain.Group;
import com.ruoyi.yipaiju.service.IGroupService;
import com.ruoyi.yipaiju.service.IXcxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/groups")
public class GroupsController extends BaseController {

    @Autowired
    private IGroupService groupService;
    @Autowired
    private IXcxUserService xcxUserService;

    @GetMapping("")
    public TableDataApi list(Group group) {
        startPageApi();
        List<Group> groups = groupService.selectGroupList(group);
        return getTableApi(groups);
    }

    /**
     * 获取组下的用户，支持集合
     * @param group
     * @return
     */
    @PostMapping("users")
    public TableDataApi users(@RequestBody Group group) {
        if (group.getGroupIds() != null && group.getGroupIds().size() > 0){
            startPageApi();
            List<XcxUser> xcxUsers = groupService.selectGroupUserList(group);
            return getTableApi(xcxUsers);
        }
        return getTableApi(new ArrayList<>());
    }

    /**
     * 设置用户所在组
     * @param groupId
     * @param userId
     * @return
     */
    @PutMapping("/{groupId}/users/{userId}")
    public ApiResult setGroupUser(@PathVariable("groupId") Long groupId, @PathVariable("userId") Long userId)
    {
        XcxUser xcxUser = xcxUserService.selectXcxUserById(userId);
        if (xcxUser != null){
            xcxUser.setGroup_id(groupId);
            xcxUserService.updateXcxUser(xcxUser);
            return ApiResult.success();
        }
        return ApiResult.error();
    }

    /**
     * 删除用户所在组
     * @param groupId
     * @param userId
     * @return
     */
    @DeleteMapping("/{groupId}/users/{userId}")
    public ApiResult delGroupUser(@PathVariable("groupId") Long groupId, @PathVariable("userId") Long userId)
    {
        XcxUser xcxUser = xcxUserService.selectXcxUserById(userId);
        if (xcxUser != null){
            xcxUser.setGroup_id(null);
            xcxUserService.updateXcxUser(xcxUser);
            return ApiResult.success();
        }
        return ApiResult.error();
    }

    /**
     * 删除组
     * @param groupId
     * @return
     */
    @DeleteMapping("/{groupId}")
    public ApiResult remove(@PathVariable Long groupId)
    {
        return groupService.deleteGroupById(groupId) > 0 ? ApiResult.success() : ApiResult.error();
    }

    /**
     * 创建组
     * @param group
     * @return
     */
    @PostMapping("/create/leaf")
    public ApiResult createLeaf(@RequestBody Group group){
        groupService.insertGroup(group);
        return ApiResult.success();
    }
}
